package ru.gr.alphaversion;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.google.zxing.client.android.PreferencesActivity;

import android.app.AlertDialog;
import android.app.TabActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.*;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TextView;
import android.widget.Toast;

public class Main extends TabActivity  {
	
	public static Main self; 
	public static ArrayList cl_tovars_main = null;
	public static String list_id, MId;
	public static String summ;
	public static int checkk = 0;
	public static int pushq = 0;
	public static String id_item, name_item, price_item, desc, qua_item, in_list_id;
	public static TextView id_l, tv1;
	public static TabHost tabHost;
	public boolean onl;
	SharedPreferences sp;
	
	
	public void onCreate(Bundle savedInstanceState) {
		sp = PreferenceManager.getDefaultSharedPreferences(this);
		System.out.println(Integer.parseInt(sp.getString("list","0")));
		switch (Integer.parseInt(sp.getString("list","0"))) {
		case 2:
			setTheme(android.R.style.Theme_Light_NoTitleBar_Fullscreen);
			System.out.println("выбрано 2");
			break;
		case 1: 
			setTheme(android.R.style.Theme_Black_NoTitleBar_Fullscreen);
			System.out.println("выбрано 1");
			break;
		default:
			setTheme(android.R.style.Theme_Black_NoTitleBar_Fullscreen);
			System.out.println("выбрано 0");
		}
		//setTheme(android.R.style.Theme_Light_NoTitleBar_Fullscreen);
	    super.onCreate(savedInstanceState);
	    
	    setContentView(R.layout.main);
	    sp = PreferenceManager.getDefaultSharedPreferences(this);
	    String listValue = sp.getString("list", "не выбрано");
	    checkk = 0;
	    self = this;
	    onl = isOnline();
	    
	    
	    
	  /*  AlertDialog.Builder alert = new AlertDialog.Builder(this);
		alert.setTitle("Введите логин и пароль");
		// Set an EditText view to get user input
		final EditText input = new EditText(this);
		final EditText input1 = new EditText(this);
		alert.setView(input);
		alert.setView(input1);
		alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				String value = input.getText().toString();
				String value1 = input1.getText().toString();
				Main.MId = login(value,value1);
			}
		});
		alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				// Canceled.
			}
		});
		alert.show();
	    */
	    if (true){
	    cl_tovars_main = new ArrayList();
	    if(list_id == null) {
	    	
	  }
	    Main.summ="0.0";
	    id_l = (TextView)findViewById(R.id.e_id);
        id_l.setText(Main.list_id);
        tv1 = (TextView)findViewById(R.id.e_summ);
       // tv1 = (TextView)findViewById(R.id.e_summ);
		tv1.setText(Main.summ);			
        
		/*	if (list_id==null) {
				//abs = false;
				new AlertDialog.Builder(this)
	            .setTitle("Ошибка связи")
	            .setMessage("Невозможно получить ID заказа")
	            .setPositiveButton("Повтор", new DialogInterface.OnClickListener() {
	            	public void onClick(DialogInterface dialog, int which) {
	            		dialog.dismiss();
	            	}
	            })
	            .setNegativeButton("Выход", new OnClickListener() {
	                public void onClick(DialogInterface dialog, int arg1) {
	                    dialog.dismiss();
	                    Main.super.onBackPressed();
	                }
	            })
	            .create().show();
				try {
					Thread.sleep(4000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			} else {
				abs = false;
			}
		} while (abs);*/
	   // Resources res = getResources(); // Resource object to get Drawables
		
		
		
	    tabHost = getTabHost();  // The activity TabHost
	    TabHost.TabSpec spec;  // Reusable TabSpec for each tab
	    Intent intent;  // Reusable Intent for each tab
	    View v;
	    
	    intent = new Intent().setClass(this, Orders.class);
	  //  v = new MyView(this, R.drawable.custom, R.drawable.custom, );
	    spec = tabHost.newTabSpec("orders").setIndicator("Заказы")
	                  .setContent(intent);
	    tabHost.addTab(spec);
	    // Create an Intent to launch an Activity for the tab (to be reused)
	 
	    
	   	    
	    intent = new Intent().setClass(this, Finder.class);
	    
	    // Initialize a TabSpec for each tab and add it to the TabHost
	  //  v = new MyView(this, R.drawable.custom, R.drawable.custom, );
	    spec = tabHost.newTabSpec("find").setIndicator("Поиск")
	                  .setContent(intent
	    			.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
	    tabHost.addTab(spec);
	 // Do the same for the other tabs //
	    intent = new Intent().setClass(this, Cats.class);
	 //   v = new MyView(this, R.drawable.custom, R.drawable.custom, );
	    spec = tabHost.newTabSpec("cats").setIndicator("Каталог")
	                  .setContent(intent
	      	    			.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
	    tabHost.addTab(spec);
	    
	   /* intent = new Intent().setClass(this, testlist.class);
		 //   v = new MyView(this, R.drawable.custom, R.drawable.custom, );
		    spec = tabHost.newTabSpec("testlist").setIndicator("Лист")
		                  .setContent(intent
		      	    			.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
		    tabHost.addTab(spec);
	    */
	    // Do the same for the other tabs //
	    intent = new Intent().setClass(this, ItemList.class);
	//    v = new MyView(this, R.drawable.custom, R.drawable.custom, );
	    spec = tabHost.newTabSpec("list").setIndicator("Список")
	                  .setContent(intent);
	    tabHost.addTab(spec);
	   // setTabColors(tabHost);
	   	    
	  

	    tabHost.setCurrentTab(0);
	    

/*	    AlertDialog.Builder alert = new AlertDialog.Builder(this);
		alert.setTitle("Введите название нового заказа");
		// Set an EditText view to get user input
		final EditText input = new EditText(this);
		alert.setView(input);
		alert.setPositiveButton("Создать", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				String value = input.getText().toString();
				Main m = new Main();
				m.addNameList(value);
				//getList();
			}
		});
		alert.setNegativeButton("Отмена", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				// Canceled.
			}
		});
		alert.show();*/
    	
			   
		
	    
	    
	    tabHost.setOnTabChangedListener(new OnTabChangeListener() {
	        public void onTabChanged(String tabId) {
	        	//Intent intent; 
	        	//TabHost.TabSpec spec; 
	        //	View an = tabHost.getCurrentView();
	        /*	tabHost.getTabWidget().removeView(tabHost.getTabWidget().getChildTabViewAt(2));
	        	intent = new Intent().setClass(Main.this, Finder.class);
	    	    spec = tabHost.newTabSpec("find").setIndicator("Поиск")
	    	                  .setContent(intent);
	    	    tabHost.addTab(spec);*/
	        	//tabHost.removeViewAt(3);
	        	//((ViewGroup) an).removeView(an);
	        //	setTabColors(tabHost);
	       //   Toast.makeText(getBaseContext(), "tabId = " + tabId, Toast.LENGTH_SHORT).show();
	        }
	      });
	      
	}
	    
	} 
	
	private void setTabColors(final TabHost tabHost) {
		for (int i = 0; i < tabHost.getTabWidget().getChildCount(); i++) { 
		tabHost.getTabWidget().getChildAt(i).getLayoutParams().height = 60;
		tabHost.getTabWidget().getChildAt(i).setBackgroundColor(Color.LTGRAY);
		} 

		tabHost.getTabWidget().getChildAt(tabHost.getCurrentTab())
		//.setBackgroundColor(Color.WHITE);
		.setBackgroundColor(Color.rgb(40, 108, 255)); 
		}
	
	
	
	
	
	protected void onSaveInstanceState(Bundle outState) {
	    super.onSaveInstanceState(outState);
	    outState.putString("list_id", list_id);
	    outState.putString("Mid", MId);
	   // System.out.println("save "+ list_id);
	    //Log.d(LOG_TAG, "onSaveInstanceState");
	  }
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
	    super.onRestoreInstanceState(savedInstanceState);
	    list_id = savedInstanceState.getString("list_id");
	    MId = savedInstanceState.getString("Mid");
	  //  System.out.println("resu "+ list_id);
	  //  Log.d(LOG_TAG, "onRestoreInstanceState");
	  }
	
	 @Override
	  protected void onDestroy() {
	    super.onDestroy();
	    Main.list_id=null;
	  }
	 
	 protected void onResume() {
		// setTheme(android.R.style.Theme_Black_NoTitleBar_Fullscreen);
		    super.onResume();
		//    String listValue = sp.getString("list", "не выбрано");
		  //  System.out.println(listValue+"123123");
		  }
	
	 public boolean isOnline() {
		    ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
		    NetworkInfo nInfo = cm.getActiveNetworkInfo();
		    if (nInfo != null && nInfo.isConnected()) {
		        Log.v("status", "ONLINE");
		        return true;
		    }
		    else {
		        Log.v("status", "OFFLINE");
		        return false;
		    }
		}
	public void addNameList(String order_name)
	{
		  Boolean abs = true;
		    
		    GetJSON json = new GetJSON();
		    do {
				try {	
					String gg = json.postData(Main.MId,order_name, "QAddNameList", "", this);
					JSONObject jsonObject = new JSONObject(gg);
					Main.list_id = jsonObject.getString("id");
					abs = false;
					Main.id_l.setText(Main.list_id);
					Main.tv1.setText("0.0");
					//id_l = (TextView)findViewById(R.id.e_id);
					for (int i=cl_tovars_main.size()-1;i>=0;i--) {
		    			cl_tovars_main.remove(i);}
			        id_l.setText(Main.list_id);
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					new AlertDialog.Builder(this)
		            .setTitle("Ошибка связи")
		            .setMessage("Невозможно получить ID заказа")
		            .setPositiveButton("Повтор", new DialogInterface.OnClickListener() {
		            	public void onClick(DialogInterface dialog, int which) {
		            		dialog.dismiss();
		            	}
		            })
		            .setNegativeButton("Выход", new OnClickListener() {
		                public void onClick(DialogInterface dialog, int arg1) {
		                    dialog.dismiss();
		                    onBackPressed();
		                }
		            })
		            .create().show();
				}
		    } while (abs);
		    
	}
	 
	public void addItem(String id_in_list, String item, String quantity, String price, String id_item) {
			
			
		CL_ListItem cl_row = new CL_ListItem();
		if (item != "") {
			//if (cl_row.getTovar_name()=="null")
			//{
			cl_row.setID(id_in_list);
			cl_row.setTovar_name(item);
			cl_row.setTovar_cena(price);
			cl_row.setTovar_id(id_item);
			//cl_row.setTovar_ost(Integer.toString(1));
			if (quantity.equals("")) {
				cl_row.setTovar_quantity("1");
			}
			else {
				cl_row.setTovar_quantity(quantity);
			}
			cl_tovars_main.add(cl_row);
			finalSum();
    	}
		//}
		//else 
		//	changeItem(Integer.parseInt(id_in_list), quantity);
	}
	
	
	public void delItem(int id) {
		CL_ListItem cl_row = (CL_ListItem) cl_tovars_main.get(id);
		String Id1 = cl_row.getId();
		Log.d("O_o", "Item ID at POSITION:"+Id1);
		GetJSON json = new GetJSON();
		try {
			json.postData(Id1, "QDelItem", "", "", this);
			finalSum();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		cl_tovars_main.remove(id);
	}
	
	public boolean changeItem(int id, String qua){
		final CL_ListItem cl_row = (CL_ListItem) cl_tovars_main.get(id);
		final String Id1 = cl_row.getId();
		if (isHave(cl_row.getTovar_id(),qua))
		{
			
		
		final GetJSON json = new GetJSON();
                	try {
            			json.postData(Id1,"", "QEditItem", qua, Main.this);
            			cl_row.setTovar_quantity(qua);
            			finalSum();
            		} catch (JSONException e) {
            			// TODO Auto-generated catch block
            			e.printStackTrace();
            		}
        return true;        	
		}
		
		else
		{
			return false;
		}
	}
	
	public boolean isHave(String str, String qua)  
    {  
		final GetJSON json = new GetJSON();
    	boolean result = false;
		try {
    		String gg = json.postData(str,"", "QGetQua","", Main.this);
			JSONObject jsonObject = new JSONObject(gg);
			if(gg!="") {
			if(jsonObject.getString("error").equals("1")) {
				Toast.makeText(this, R.string.no_name, Toast.LENGTH_LONG).show();
			}
				else {
				
							String MId = jsonObject.getString("qua");
						//	Toast.makeText(this, MId, Toast.LENGTH_LONG).show();
							if (Integer.parseInt(MId)>=Double.parseDouble(qua)){
								result = true;
							}
							else {
								//ItemList parent = (ItemList)getParent();
						//		Context a = getBaseContext();
							//	int c =1;
							//	Toast toast = Toast.makeText(getApplicationContext(), "Неверное количество товара/n Доступно:"+MId, Toast.LENGTH_LONG);
			        	//		toast.setGravity(Gravity.CENTER, 0, 0);
							//	  LinearLayout toastView = (LinearLayout) toast.getView();
							//        ImageView imageWorld = new ImageView(getApplicationContext());
							//        imageWorld.setImageResource(R.drawable.ic_launcher);
							//        toastView.addView(imageWorld, 0);
			        			//toast.show();
								result = false;
								}
							}
			} else {
				result = false;
			}
			
    	} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			result = false;
		}
    	
    	return result;
      }
	
	
	
	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.layout.main_menu, menu);
        return true;
    }
	
	public void finalSum() {
		float k = 0;
		Main.tv1.setText("0.0");
		if(cl_tovars_main.size()!=0){
			for (int i=cl_tovars_main.size()-1;i>=0;i--) {
				CL_ListItem cl_row = (CL_ListItem) cl_tovars_main.get(i);
				k += Float.parseFloat(cl_row.getTovar_cena())*Double.parseDouble(cl_row.getTovar_quantity());
			}
		}
		
		
		k = k*100;
		k = Math.round(k);
		k = k/100;
		//Math.rint(k);
		//Main.tv1 = (TextView)findViewById(R.id.e_summ);
		Main.tv1.setText(Float.toString(k));
				
	}
	
	
	@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
    /*    case R.id.create_order:
        	AlertDialog.Builder alert = new AlertDialog.Builder(this);
    		alert.setTitle("Введите название нового заказа");
    		// Set an EditText view to get user input
    		final EditText input = new EditText(this);
    		alert.setView(input);
    		alert.setPositiveButton("Создать", new DialogInterface.OnClickListener() {
    			public void onClick(DialogInterface dialog, int whichButton) {
    				String value = input.getText().toString();
    				Main m = new Main();
    				m.addNameList(value);
    				//getList();
    			}
    		});
    		alert.setNegativeButton("Отмена", new DialogInterface.OnClickListener() {
    			public void onClick(DialogInterface dialog, int whichButton) {
    				// Canceled.
    			}
    		});
    		alert.show();
        	
        return true;
      */  
        case R.id.quit:
        	new AlertDialog.Builder(this)
            .setTitle("Закрыть?")
            .setMessage("Вы действительно хотите закрыть приложение?")
            .setNegativeButton(android.R.string.no, null)
            .setPositiveButton(android.R.string.yes, new OnClickListener() {

                public void onClick(DialogInterface arg0, int arg1) {
                    Main.super.onBackPressed();
                    finish();
                }
            }).create().show();
            return true;
        case R.id.version:
        	new AlertDialog.Builder(this)
            .setTitle("О Гипербаза-beta")
            .setMessage("Гипербаза-beta 0.844")
            .setPositiveButton("Назад", new DialogInterface.OnClickListener() {
            	public void onClick(DialogInterface dialog, int which) {
            		dialog.dismiss();
            	}
            })
            .create().show();
            return true;
        case R.id.list_del:
        	new AlertDialog.Builder(this)
            .setTitle("Очистить?")
            .setMessage("Вы действительно хотите очистить список?")
            .setNegativeButton(android.R.string.no, null)
        	.setPositiveButton(android.R.string.yes, new OnClickListener() {
        		public void onClick(DialogInterface arg0, int arg1) {
        			GetJSON json = new GetJSON();
    		try {
    			json.postData(list_id, "", "QDelList", "", Main.this);    			
    		} catch (JSONException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    		for (int i=cl_tovars_main.size()-1;i>=0;i--) {
    			cl_tovars_main.remove(i);
    		}
    		Main.tv1.setText("0.0");
    		Main.list_id=null;
    		 id_l.setText(Main.list_id);
    		TabHost tabHost = getTabHost();  // The activity TabHost
    	    tabHost.setCurrentTab(0);
        		}
            }).create().show();        	
        	return true;
        case R.id.list_order:
        	new AlertDialog.Builder(this)
            .setTitle("Отправить заказ?")
            .setMessage("Вы действительно хотите отправить заказ?")
            .setNegativeButton(android.R.string.no, null)
        	.setPositiveButton(android.R.string.yes, new OnClickListener() {
        		public void onClick(DialogInterface arg0, int arg1) {
        			GetJSON json = new GetJSON();
    		try {
    			json.postData(list_id, MId, "QOrderList", "", Main.this);    			
    		} catch (JSONException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    		/*for (int i=cl_tovars_main.size()-1;i>=0;i--) {
    			cl_tovars_main.remove(i);
    		}*/
    		TabHost tabHost = getTabHost();  // The activity TabHost
    	    tabHost.setCurrentTab(0);
        		}
            }).create().show();        	
        	return true;
        case R.id.prefs:
        	item.setIntent(new Intent(this, Prefs.class));
        
        	return super.onOptionsItemSelected(item);
        case R.id.prefsqr:
        	item.setIntent(new Intent(this, PreferencesActivity.class));
        
        	return super.onOptionsItemSelected(item);
        	
      default:
            return super.onOptionsItemSelected(item);
        }
	}
	
	public String login(String value, String value1) {
		
		  GetJSON json = new GetJSON();
		    try {
					String gg = json.postData("",value, "QLogin", value1, this);
					JSONObject jsonObject = new JSONObject(gg);
					if(gg!="") {
					if(jsonObject.getString("error").equals("1")) {
						Toast.makeText(this, R.string.no_name, Toast.LENGTH_LONG).show();
					}
						else {
						
									String MId = jsonObject.getString("id");
									Toast.makeText(this, MId, Toast.LENGTH_LONG).show();
									return MId;
					//abs = false;
					//Main.id_l.setText(Main.list_id);
					//id_l = (TextView)findViewById(R.id.e_id);
			        //id_l.setText(Main.list_id);
				
				
						}
					}
				else {
					String MId = "0";
					//Toast.makeText(this, "Нет соединения с сервером", Toast.LENGTH_LONG).show();
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				new AlertDialog.Builder(this)
	            .setTitle("Ошибка связи")
	            .setMessage("Невозможно получить ID заказа")
	            .setPositiveButton("Повтор", new DialogInterface.OnClickListener() {
	            	public void onClick(DialogInterface dialog, int which) {
	            		dialog.dismiss();
	            	}
	            })
	            .setNegativeButton("Выход", new OnClickListener() {
	                public void onClick(DialogInterface dialog, int arg1) {
	                    dialog.dismiss();
	                    onBackPressed();
	                }
	            })
	            .create().show();
			}
			return MId;
		   
	}
	
	
	public void orderItemList() {
		Main.id_l.setText(Main.list_id);
		Main.tv1.setText("0.0");
		//Main mn = new Main();
		for (int i=Main.cl_tovars_main.size()-1;i>=0;i--) {
			Main.cl_tovars_main.remove(i);
		}
		GetJSON json = new GetJSON();
		try {
			//Main.list_id = editText.getText().toString();
			
			//TextView id_l = (TextView)mn.findViewById(R.id.e_id);
		    //id_l.setText(Main.list_id);
			//outState.putString("list_id", list_id);
			String gg = json.postData(Main.list_id, "", "QGetList", "", this);
			JSONObject jsonObject = new JSONObject(gg);
			if(gg!="") {
				if(jsonObject.getString("error").equals("1")) {
					//Toast.makeText(this, "Нет такого заказа", Toast.LENGTH_LONG).show();
				} else {
					//JSONArray jsonArray = new JSONArray(jsonObject.getString("items"));
					//JSONObject jsonObject_1 = jsonArray.getJSONObject(0);
					if (jsonObject.getJSONArray("items")!=null){
					JSONArray jsonObject_1 = jsonObject.getJSONArray("items");
					System.out.println(jsonObject_1.length());
					//Main.tv1.setText("0.0");
					for (int i = 0; i<(jsonObject_1.length()); i++) {
						System.out.println(jsonObject_1.getJSONObject(i)
								.getString("NAME").toString());
						System.out.println(jsonObject_1.getJSONObject(i).getString(
								"ID").toString());
						
					 
					Main.desc = jsonObject_1.getJSONObject(i).getString("NAME");
							//+"\n"+"ID: "+jsonObject_1.getJSONObject(i).getString("ITEMID");
					Main.id_item = jsonObject_1.getJSONObject(i).getString("ITEMID");
					Main.in_list_id = jsonObject_1.getJSONObject(i).getString("INID");
					Main.price_item = jsonObject_1.getJSONObject(i).getString("PRICE");
					Main.qua_item = jsonObject_1.getJSONObject(i).getString("QUANTITY");
					addItem(Main.in_list_id,Main.desc,Main.qua_item,Main.price_item,Main.id_item);
					}
					
					}
					/*Intent findItem_1 = new Intent(this, Main.class);
					findItem_1.putExtra("itemId",jsonObject_1);
					findItem_1.putExtra("price_item", price_item);
					findItem_1.putExtra("desc", desc);
					findItem_1.putExtra("qua_item", qua_item);*/
					Log.d("asdfghjkkjh", Main.id_item);
					}
			}
					//Finder ff = (Finder)getParent();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		/*for (int i=cl_tovars_main.size()-1;i>=0;i--) {
			cl_tovars_main.remove(i);
		}*/
		//Main.tabHost = getTabHost();  // The activity TabHost
		Main.tabHost.setCurrentTab(3);
	}
	
	
	    
}